<?php
// +-------------------------
// | 控制器基础类
// +-------------------------
namespace Framework\Core; 
  
class Model {
 
	protected $tableName; //当前要操作的表名 $tableName = modelName
	protected $sqlBlock = array();
 	private   $sql = '';

	function __construct($tableName = '') {



		$this->tableName = $tableName; 
 
		$this->sqlBlock = array(
				'action' => '',  //SELECT UPDATE DELETE INSERT INTO
				'field'  => '*',  // str  array
				'table'  => "`$this->tableName`", // str
				'where'  => '',  // array str
				'order'  => '',	 // str:id DESC
				'limit'  => '',  // str
				'sub_action' => '',  //find
			);
		
	}

	/**
	 * 条件语句
	 * @param  array
	 */
	public function where($data) {

		$str = "WHERE ";
		$arr = array();

		if (is_array($data)) {

			foreach ($data as $key => $value) {
				$arr[] = " `$key` = '$value' ";
			}

			$str .= implode('AND', $arr);

		} else if (is_string($data)) {
			$str .= $data;
		} else {
			return FALSE;
		}
   
		$this->sqlBlock['where'] = $str;

		return $this;
	}


	/**
	 * 字段组合
	 * @param string|array $field  
	 */
	public function field($field = '*') {

		$this->sqlBlock['field'] = $field;

		return $this;
	}

	/**
	 * Limit组合
	 * @param str
	 */
	public function limit($limit = '') {

		$this->sqlBlock['limit'] = $limit;

		return $this;
	}

	/**
	 * Order组合
	 * @param str
	 */
	public function order($order = '') {
		
		$this->sqlBlock['order'] = $order;

		return $this;
	}


	/**
	 * 添加
	 */
	public function add($data) {
		//INSERT INTO documents (`group_id`,`group_id2`,`date_added`,`title`,`content`) VALUES(2,3,4,5,6)
		$this->sqlBlock['action'] = 'INSERT INTO';
		$this->sqlBlock['field']  = $data;

		$this->_parseSql();
		return;
	}

	/**
	 * 更新
	 */
	public function save($data) {
		//UPDATE `documents` SET `id` = 444 WHERE `id` = 1;
		$this->sqlBlock['action'] = 'UPDATE';
		$this->sqlBlock['field']  = $data;

		$this->_parseSql();
		return;
	}

	/**
	 * 删除
	 */
	public function delete() {
		$this->sqlBlock['action'] = 'DELETE';

		$this->_parseSql();
		return;
	}

	/**
	 * 查询全部
	 */
	public function select() {
		$this->sqlBlock['action'] = 'SELECT';
		
		$this->_parseSql();
		
		return $this->fetchAll();
	}


	/**
	 * 查询一条
	 */
	public function find() {
		$this->sqlBlock['action'] = 'SELECT';
		$this->sqlBlock['sub_action'] = 'find';


		$this->_parseSql();
		return $this->fetchOne();;
	}


	/**
	 * SQL解析
	 */
	private function _parseSql() {

		if (is_array($this->sqlBlock['field'])) {
			//field 字段的处理

			switch($this->sqlBlock['action']) {
				case 'UPDATE':
					//更新操作时 field字段=>值 的组合
					$str = '';
					$arr = array();
					foreach ($this->sqlBlock['field'] as $key => $value) {
						$arr[] = "`{$key}` = '{$value}'";
					}
					$this->sqlBlock['field'] = implode(',', $arr);
					break;
				case 'SELECT':
					//查询操作时 field字段=>值 的组合
					$this->sqlBlock['field'] = implode(',', $this->sqlBlock['field']);
					break;
				case 'INSERT INTO':
					//写入操作时 field字段的处理

					$fieldStr = '(';
					$valueStr = '(';
					$fieldStrArr    = array();
					$valueStrStrArr = array();

					foreach ($this->sqlBlock['field'] as $field => $value) {
						$fieldStrArr[] = "`{$field}`";
						$valueStrStrArr[] = "'{$value}'";
					}

					$fieldStr .= implode(',', $fieldStrArr) . ')';
					$valueStr .= implode(',', $valueStrStrArr) . ')';

					$this->sqlBlock['field'] = $fieldStr.' VALUES '.$valueStr;

					break;
			}



		}


		//操作符以及sql数组的处理
		switch ($this->_getAction()) {
			case 'SELECT':
				$delimiter = 'FROM';
				$insertArr = array('delimiter'=>$delimiter); //插入的分隔符
				$this->sqlBlock = insert_to_array($this->sqlBlock, $insertArr, 'field:after');
				
				break;
			case 'UPDATE':
				//调整分隔符的位置 拼装sql语句

				$delimiter = 'SET';
				$insertArr = array('delimiter'=>$delimiter);

				$this->sqlBlock = array_element_reverse($this->sqlBlock, 'field', 'table');
				$this->sqlBlock = insert_to_array($this->sqlBlock, $insertArr, 'table:after');

				break;
			case 'DELETE':
				unset($this->sqlBlock['field']);

				// if (empty($this->sqlBlock['where'])) {
				// 	return false; //防止误删
				// }

				$delimiter = 'FROM';
				$insertArr = array('delimiter'=>$delimiter); //插入的分隔符
				$this->sqlBlock = insert_to_array($this->sqlBlock, $insertArr, 'table:before');

				break;

			case 'INSERT INTO':

				$this->sqlBlock = array_element_reverse($this->sqlBlock, 'table', 'field');

				break;

			default:
				echo 'null';
		}


		$this->sql = $this->_createSql();

	}

	private function _createSql() {
		$temp_sub_action = $this->sqlBlock['sub_action'];
		unset($this->sqlBlock['sub_action']);

		foreach ($this->sqlBlock as $key => $value) {
			if (empty($this->sqlBlock[$key])) unset($this->sqlBlock[$key]);
		}

		$sql = implode(' ', $this->sqlBlock);

		return $sql;
	}


	private function _getAction() {
		return $this->sqlBlock['action'];
	}


	public function query($sql) {
		return Db::query($sql);
	}

	public function fetchAll() {
		return Db::fetchAll($this->sql);
	}

	public function fetchOne() {
		return Db::fetchOne($this->sql);
	}

	public function showTables() {
		return Db::showTables();
	}



}
